package com.hzmall.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;

@Slf4j
public class FtpUtil {
    private static String ftpIp = PropertiesUtil.getStringProperty("ftp.server.ip");
    private static String ftpUsername = PropertiesUtil.getStringProperty("ftp.user");
    private static String ftpPassword = PropertiesUtil.getStringProperty("ftp.pass");

    private String ip;
    private String username;
    private String password;

    private static FTPClient ftpClient;

    private FtpUtil(String ip, String username, String password) {
        this.ip = ip;
        this.username = username;
        this.password = password;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    public static Boolean uploadFile(List<File> fileList) throws Exception{
        FtpUtil ftpUtil = new FtpUtil(ftpIp,ftpUsername,ftpPassword);
        log.info("开始连接FTP，地址{}",ftpIp+":"+21);
        boolean result = ftpUtil.uploadFile("img",fileList);
        log.info("上传完成");
        return result;
    }
    private Boolean uploadFile(String remotePath,List<File> fileList) throws Exception{
        boolean uploaded = false;
        FileInputStream fis = null;
        if (connectFTPServer(ftpIp,ftpUsername,ftpPassword)){
            try {
                ftpClient.changeWorkingDirectory(remotePath); //更改存放路径
                ftpClient.setBufferSize(1024);
                ftpClient.setControlEncoding("UTF-8");
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  //存储模式 二进制
                ftpClient.enterLocalPassiveMode();
                for (File fileItem : fileList){
                    fis = new FileInputStream(fileItem);
                    ftpClient.storeFile(fileItem.getName(),fis);
                }
                uploaded = true;
            }catch (Exception e){
                log.error("文件上传异常",e);
                e.printStackTrace();
            }finally {
                fis.close();
                ftpClient.disconnect();
            }
        }
        return uploaded;
    }
    private boolean connectFTPServer(String ip, String username, String password){
        boolean isConnected = true;
        ftpClient = new FTPClient();
        try {
            ftpClient.connect(ip);
            ftpClient.login(username,password);
        }catch (Exception e){
            isConnected = false;
            log.error("连接FTP异常",e);
        }
        return isConnected;
    }
}
